package com.ctshk.common.web.support;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.Assist;
import com.ctshk.common.utils.RSAUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @description 公共controller基类
 * @author 谢诗宏
 * @date 2020/12/18
 */
@Slf4j
public class BaseController {

    /**
     * 得到request对象
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 得到response对象
     */
    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取当前用户
     * @param request
     * @return
     */
    public TokenUser getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader(RedisConstants.JWT_TOKEN_HEADER);
        if (StringUtils.isBlank(token)) {
            throw new BusinessException(SystemError.USER_1000);
        }
        TokenUser tokenUser = new TokenUser();
        try {
            token = token.replace(RedisConstants.JWT_TOKEN_PREFIX, Strings.EMPTY);
            String tokenDecrypt = RSAUtil.decryptStr(token);
            tokenUser = JSONObject.parseObject(tokenDecrypt, TokenUser.class);
        } catch (Exception e) {
            throw new BusinessException(SystemError.USER_1015);
        }

        return tokenUser;
    }

    /**
     * 获取当前登录用户 允许未登录
     * @param request
     * @return
     */
    public TokenUser getCurrentUserAllowNotLogIn(HttpServletRequest request){
        String token = request.getHeader(RedisConstants.JWT_TOKEN_HEADER);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        TokenUser tokenUser = new TokenUser();
        try {
            token = token.replace(RedisConstants.JWT_TOKEN_PREFIX, Strings.EMPTY);
            String tokenDecrypt = RSAUtil.decryptStr(token);
            tokenUser = JSONObject.parseObject(tokenDecrypt, TokenUser.class);
        } catch (Exception e) {
            throw new BusinessException(SystemError.USER_1015);
        }
        return tokenUser;
    }

    /**
     * 获取当前登录用户 允许未登录
     * @param
     * @return
     */
    public TokenUser getCurrentUserAllowNotLogIn() {
    	return getCurrentUserAllowNotLogIn(getRequest());
    }

    /**
     * 获取当前登录用户 允许未登录
     * @param
     * @return
     */
    public Long getCurrentUserAllowNotLogInUserId() {
        TokenUser currentUserAllowNotLogIn = getCurrentUserAllowNotLogIn(getRequest());
        if(currentUserAllowNotLogIn != null) {
            return currentUserAllowNotLogIn.getId();
        }
        return null;
    }

    /**
     * 获取当前用户
     * @param request
     * @return
     */
    public TokenUser getCurrentUser() {
        return getCurrentUser(getRequest());
    }
    
    /**
     * 获取当前用户
     * @param request
     * @return
     */
    public Long getCurrentUserId() {
    	return Assist.ifNotNullFn(getCurrentUser(), TokenUser::getId);
    }

    /**
     * id字符串转换成idList
     * @param ids ids
     * @return
     */
    public List<Long> formatIds(String ids) {
    	if (ids == null) {
    		return null;
		}
        List<Long> id = new ArrayList<>();
        String[] strings = ids.split(",");
        for (String string : strings) {
            id.add(Long.valueOf(string));
        }
        return id;
    }

    /**
     * 时间查询区间字符串转换
     * @param startTime
     * @return
     */
    public Map<String, String> formatStartTime(String startTime) {
    	Map<String, String> map = new HashMap<String, String>();
    	if (StringUtils.isNotBlank(startTime)) {
        	String[] parts = startTime.split(" - ");
        	map.put("startTime", parts[0]);
        	map.put("endTime", parts[1]);
		}
        return map;
    }
}
